package com.icodingedu.springcloud.controller;

import com.icodingedu.springcloud.pojo.PortInfo;
import com.icodingedu.springcloud.service.MyService;
import com.icodingedu.springcloud.service.RequestCacheService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class HystrixController {

    @Resource
    private MyService myService;

    @Autowired
    private RequestCacheService requestCacheService;

    @GetMapping("/fallback")
    public String fallback(){
        return myService.error();
    }

    @GetMapping("/timeout")
    public String timeout(int second){
        return myService.retry(second);
    }

    @GetMapping("/cache")
    public PortInfo requestCache(String name){
        @Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
        PortInfo portInfo = requestCacheService.requestCache(name);
        portInfo = requestCacheService.requestCache(name);
        portInfo = requestCacheService.requestCache(name);
        return portInfo;
    }


    @GetMapping("/timeout2")
    @HystrixCommand(
            fallbackMethod = "timeoutfallback",
            //ignoreExceptions = {IllegalArgumentException.class}
            commandProperties = {
                    @HystrixProperty(
                            name = "execution.isolation.thread.timeoutInMilliseconds",
                            value = "3000"
                    )
            }
    )
    public String timeout2(int second){
        return myService.retry(second);
    }

    public String timeoutfallback(int second){
        return "timeoutfallback success .... "+second;
    }
}
